package com.thinkgem.jeesite.modules.devmng.service;

import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.service.ServiceException;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.devmng.dao.MultitaskingDao;
import com.thinkgem.jeesite.modules.devmng.entity.*;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import org.apache.commons.collections.map.LinkedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service
@Transactional(readOnly = true)
public class MultitaskingService extends CrudService<MultitaskingDao, Multitasking> {
    @Autowired
    private TaskDeviceDevchkItemService taskDeviceDevchkItemService;

    @Autowired
    private DevchkItemService devchkItemService;

    @Autowired
    private DeviceMainService deviceMainService;

    @Autowired
    private SystemService systemService;

    @Autowired
    private TaskDetailService taskDetailService;

    @Autowired
    private TaskMainService taskMainService;

    @Transactional(readOnly = false)
    public void delete(Multitasking multitasking) {
        super.delete(multitasking);
    }

    @Transactional(readOnly = false)
    public Multitasking get(String multitasking) {
        return super.get(multitasking);
    }

    @Transactional(readOnly = false)
    public void save(TaskMain taskMain) {
        Multitasking multitasking = new Multitasking();
        if (StringUtils.isNotEmpty(taskMain.getId())) {
            if (!TaskMain.Status.OPEN.name().equals(taskMain.getTaskStatus())) {
                throw new ServiceException("任务已经开始，不能进行修改！");
            }
        }
        //获取部门下的设备信息
        List<DeviceMain> officeList = deviceMainService.findListIdBySysOffice(taskMain.getSysOffice().getId());
        Set<String> onlyUser = new LinkedHashSet<>();
        Map<User, DeviceMain> deviceAndUserId = new LinkedMap();
        for (DeviceMain dm : officeList) {
            deviceAndUserId.put(dm.getDeviceUser(), dm);
            onlyUser.add(dm.getDeviceUser().getId());
        }
        String taskType = (String) taskMain.getTaskType();
        String monthFlag = "N";
        String quarterFlag = "N";
        String halfYearFlag = "N";
        String yearFlag = "N";
        String taskTitle = "";
        switch (taskType) {
            case "M":
                monthFlag = "Y";
                taskTitle = taskMain.getSysOffice().getName() + "月度计划";
                break;
            case "Q":
                quarterFlag = "Y";
                taskTitle = taskMain.getSysOffice().getName() + "季度度计划";
                break;
            case "HY":
                halfYearFlag = "Y";
                taskTitle = taskMain.getSysOffice().getName() + "半年度计划";
                break;
            case "Y":
                yearFlag = "Y";
                taskTitle = taskMain.getSysOffice().getName() + "年度度计划";
                break;
        }
        //任务模板

        taskMain.setTaskTitle(taskMain.getTaskTitle() + taskTitle);
        taskMain.setTaskStatus(TaskMain.Status.OPEN.name());
        //任务保存名
        multitasking.setTaskTitle(taskMain.getTaskTitle());
        super.save(multitasking);
        //按包机人遍历任务关系
        for (String s : onlyUser) {
            TaskMain taskMainRecord = null;
            String deviceIds = "";
            String deviceNames = "";
            for (Map.Entry<User, DeviceMain> ud : deviceAndUserId.entrySet()) {
                if (s.equals(ud.getKey().getId())) {
                    deviceIds += ud.getValue().getId() + ",";
                    deviceNames += ud.getValue().getDeviceName() + "(" + ud.getValue().getDeviceUser() + ")" + ",";
                }
            }
            //任务模板
            User user = systemService.getUser(s);
            taskMain.setSysOffice(new Office(user.getOffice().getId()));
            taskMain.setTaskOperator(user);
            taskMain.setMultiTaskId(multitasking.getId());
            taskMain.setId(null);
            taskMainRecord = taskMain;
            taskMainRecord.setId(null);
            taskMainService.saveSuper(taskMainRecord);
            // 删除旧数据
            taskDeviceDevchkItemService.deleteByTaskMainId(taskMainRecord.getId());
            taskDetailService.deleteByTaskMainId(taskMainRecord.getId());
            // 处理新数据
            String[] idsList = deviceIds.split(",");
            String[] namesList = deviceNames.split(",");
            List<TaskDetail> taskDetailList = new ArrayList<>();
            for (int i = 0; i < idsList.length; i++) {
                TaskDetail TaskDetail = new TaskDetail();
                TaskDetail.setDeviceMainId(idsList[i]);
                TaskDetail.setDeviceName(namesList[i]);
                TaskDetail.setTaskMainId(taskMainRecord.getId());
                TaskDetail.setMonthFlag(monthFlag);
                TaskDetail.setQuarterFlag(quarterFlag);
                TaskDetail.setHalfYearFlag(halfYearFlag);
                TaskDetail.setYearFlag(yearFlag);
                taskDetailList.add(TaskDetail);
                taskDetailService.save(TaskDetail);
            }
            // 遍历任务所有的设备

            Map<DevchkItem, TaskDetail> devchkItemAndDeviceMain = new LinkedHashMap<>();
            int devchkItemCount = 0;
            for (TaskDetail taskDetail : taskDetailList) {

                // 获取设备的检修项信息
                DevchkItem queryDevchkItem = new DevchkItem();
                queryDevchkItem.setDeviceMain(new DeviceMain(taskDetail.getDeviceMainId()));
                List<DevchkItem> devchkItemList = devchkItemService.findList(queryDevchkItem);
                if (devchkItemList == null || devchkItemList.size() == 0) {
                    /*deviceMainRecordTemp = taskDetail.getId();*/

                    throw new ServiceException("没有发现设备的检修项！");
                }
                // 检查任务、设备关联关系
                for (DevchkItem devchkItem : devchkItemList) {
                    boolean match = DevchkItem.CheckPeriod.Y.name().equals(devchkItem.getCheckPeriod()) && taskDetail.getYearFlag().equals("Y")
                            || DevchkItem.CheckPeriod.M.name().equals(devchkItem.getCheckPeriod()) && taskDetail.getMonthFlag().equals("Y")
                            || DevchkItem.CheckPeriod.HY.name().equals(devchkItem.getCheckPeriod()) && taskDetail.getHalfYearFlag().equals("Y")
                            || DevchkItem.CheckPeriod.Q.name().equals(devchkItem.getCheckPeriod()) && taskDetail.getQuarterFlag().equals("Y");
                    if (!match) {

                        continue;
                    }
                    devchkItemCount++;
                    devchkItemAndDeviceMain.put(devchkItem, taskDetail);

                }
                //判断 taskDetail是否符合任务
                if (devchkItemCount == 0) {
                    taskDetailService.delete(taskDetail);
                    /*taskMainService.delete(taskMainRecord);*/

                }
            }

            //关联设备,检修项,任务ID
           for (Map.Entry<DevchkItem, TaskDetail> dd : devchkItemAndDeviceMain.entrySet()) {
                dd.getValue().setTaskMainId(taskMainRecord.getId());
                TaskDeviceDevchkItem taskDeviceDevchkItem = new TaskDeviceDevchkItem();
                taskDeviceDevchkItem.setDeviceMainId(dd.getValue().getDeviceMainId());
                taskDeviceDevchkItem.setTaskMainId(taskMainRecord.getId());
                taskDeviceDevchkItem.setDevchkItemId(dd.getKey().getId());
                taskDeviceDevchkItem.setStatus(TaskDeviceDevchkItem.Status.OPEN.name());
                taskDeviceDevchkItemService.save(taskDeviceDevchkItem);
            }
            //任务是否有检修项
            if (devchkItemCount == 0) {
                taskMainService.delete(taskMainRecord);
            }


        }
    }
}


